<?php
namespace Modules\Product\Http\Controllers\Erp\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Product\Entities\Product;
use Modules\Product\Entities\ProductExt;

use Validator;
use ThrowException;
use DB;

class ProductBatchController extends Controller
{
    // 分离info
    public  function separateInfo($info)
    {
        $productInfo = [
            'title' => $info['title'],
            'thumb' => $info['thumb'],
            'number' => $info['number'],
            'ean' => @$info['ean'],
            'money_price' => @$info['money_price'],
            'score_price' => @$info['score_price'],
            'category_ids' => @$info['category_ids'],
            'outer_id' => $info['outer_id'],
            'level1_category_id' => @$info['level1_category_id'],
            'brand_id' => @$info['brand_id'],
            'status' => @$info['status'],
            'tags' => @$info['tags'],
            'supplier'  => @$info['supplier'],
            'is_need_address' => @$info['is_need_address'] ?: 1,
            'is_free_carriage' => @$info['is_free_carriage'] ?: 0,
            'carriage_type' => @$info['carriage_type'] ?: 1,
            'carriage' => @$info['carriage'],
            'is_offline_useable' => @$info['is_offline_useable'] ?: 1,
            'is_presell' => @$info['is_presell'] ?: 0,
            'presell_mode' => @$info['presell_mode'] ?: 0,
            'presell_date' => @$info['presell_date'],
            'remark' => @$info['remark'],
            'list_weight' => @$info['list_weight'] ?: 99
        ];

        $extInfo = [
            'uuid' => uniqid(),
            'images' => @$info['images'],
            'normal_attrs' => @$info['normal_attrs'],
            'sku_attrs' => @$info['sku_attrs'],
            'page' => @$info['page']
        ];

        $skusInfo = $info['skus'];

        return [
            $productInfo,
            $extInfo,
            $skusInfo
        ];
    }

    // 创建商品
    public function createProduct($info)
    {
        list($productInfo, $extInfo, $skusInfo) = $this->separateInfo($info);

        $product = Product::create($productInfo);

        $extInfo['product_id'] = $product->id;
        ProductExt::create($extInfo);

        // 保存商品sku信息
        foreach ($skusInfo as $key => $sku) {
            $skusInfo[$key]['uuid'] = uniqid();
        }
        $product->skus()->createMany($skusInfo);

        return  $product;

        // $product->updateCategoryRelation();
        // $product->updateSalesAndStock();
    }

    // 更新商品
    public function updateProduct($product, $info)
    {
        list($productInfo, $extInfo, $skusInfo) = $this->separateInfo($info);

        // 更新商品主信息
        $product->update($productInfo);

        // 更新sku信息
        // 更新 sku 
        // 删除旧sku
        $oldSkuIds = collect($skusInfo)->pluck('outer_id')->all();
        $product->skus()->whereNotIn('outer_id', $oldSkuIds)->delete();

        // 如有原sku id， 更新原sku，否则创建sku
        foreach ($skusInfo as $sku) {

            if (isset($sku['outer_id'])) {

                $skuObj = $product->skus()->where('outer_id', $sku['outer_id'])->first();

                if ($skuObj) {
                    $skuObj->update($sku);
                }
                else {
                    $sku['uuid'] = uniqid();
                    $product->skus()->create($sku);
                }
            }
            else {
                ThrowException::Conflict('sku缺少outer_id');
            }
        }

        // 更新ext信息
        $product->ext->update($extInfo);

        return  $product;
    }

    // 批量导入
    public function store(Request $req)
    {

        $rule = [
            'list' => ['required', 'array'],
            // 'thumb' => ['required'],
            // 'images' => ['array'],
            // 'skus' => ['required', 'array'],
            // 'sku_attrs' => ['required', 'array'],
            // 'status' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        foreach ($req->input('list') as $info) {

            $outerId = @$info['outer_id'] ?: ThrowException::Conflict('请传outer_id参数');

            $product = Product::where('outer_id', $outerId)->first();

            DB::beginTransaction();
            if (@$info['action_type'] === 'delete') {
                if ($product) {
                    $product->ext()->forceDelete();
                    $product->skus()->forceDelete();

                    $product->forceDelete();
                }
                // $product && $product->forceDelete();
            }
            elseif (@$info['action_type'] === 'put_off') {
                $product->update([
                    'status' => 0
                ]);
                
                // $product && $product->forceDelete();
            }
            elseif (@$info['action_type'] === 'put_on') {
                $product->update([
                    'status' => 1
                ]);
                // $product && $product->forceDelete();
            }
            elseif (!$product) {
                // 不存，则创建
                $product = $this->createProduct($info);
            }
            else {
                // 更新小程序
                $product = $this->updateProduct($product, $info);
            }
            DB::commit();

            // 更新库存
            $product->updateSalesAndStock();
        }

        return [
            'status' => 'completed'
        ];
    }
}
